import React, { Component } from 'react'
import { NavLink } from 'react-router-dom';
import store, {Types, actionCreator} from '../store'

export default class Redux extends Component {
  constructor() {
    super();
    this.state = {
      age: 0,
      name: '',
      val1: ''
    }
  }
  componentDidMount() {
    // 进入页面先回去store中的数据，放在页面上
    // this.setState(store.getState())
    let obj = store.getState();
    this.setState({
      age: obj.age,
      name: obj.name
    })
    // 订阅，简单理解为监听.每当数据变化时就会自动执行回调函数
    this.un = store.subscribe(()=>{
      this.setState(store.getState())
    })
  }
  componentWillUnmount() {
    // 取消监听
    this.un()
  }
  changeAge() {
    store.dispatch(actionCreator.ageAdd());
  }
  changeName() {
    store.dispatch(actionCreator.nameChange(this.state.val1));
  }
  render() {
    return (
      <div>
        <p>使用redux</p>
        <p>年龄：{this.state.age}</p>
        <p>姓名：{this.state.name}</p>
        <input value={this.state.val1} onChange={(e)=>this.setState({val1: e.target.value})} />
        <button onClick={()=>this.changeName()}>改名字</button>
        <button onClick={()=>this.changeAge()}>过生日</button>
        <NavLink to="/redux2">redux2</NavLink>
      </div>
    )
  }
}
